# 客户管理与单价配置相关视图
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404
from LogisticsCard.models import Customer, UserPriceConfig


@login_required
def customer_list_view(request):
    """
    客户列表视图，展示所有客户信息。
    :param request: HttpRequest对象
    :return: 渲染客户列表页面
    """
    customers = Customer.objects.filter(delete_at__isnull=True).order_by('-created_at')
    return render(request, 'customer/index.html', {'customers': customers})


@login_required

def customer_create_view(request):
    """
    客户创建视图，支持收货地址信息，并同步 Address 表（customer 关联）。
    """
    from LogisticsCard.models import Address
    if request.method == 'POST':
        username = request.POST.get('username')
        company_name = request.POST.get('company_name')
        phone = request.POST.get('phone')
        address_field = request.POST.get('address')
        email = request.POST.get('email')
        remark = request.POST.get('remark', '')
        receiver = request.POST.get('receiver')
        delivery_phone = request.POST.get('delivery_phone')
        delivery_address = request.POST.get('delivery_address')
        customer = Customer.objects.create(
            username=username,
            company_name=company_name,
            phone=phone,
            address=address_field,
            email=email,
            remark=remark,
            delete_at=None
        )
        Address.objects.create(customer=customer, receiver=receiver, phone=delivery_phone, address=delivery_address, delete_at=None)
        return redirect('customer_list')
    return render(request, 'customer/create.html')

# 客户编辑视图，支持同步修改收货地址信息
@login_required
def customer_edit_view(request, customer_id):
    from LogisticsCard.models import Address
    from django.contrib.auth.models import User
    import re
    customer = get_object_or_404(Customer, id=customer_id)
    address_obj = Address.objects.filter(customer=customer, delete_at__isnull=True).first()
    if request.method == 'POST':
        customer.username = request.POST.get('username')
        customer.company_name = request.POST.get('company_name')
        customer.phone = request.POST.get('phone')
        customer.address = request.POST.get('address')
        customer.email = request.POST.get('email')
        customer.remark = request.POST.get('remark', '')
        # 生成普通用户
        if request.POST.get('generate_user'):
            # 英文用户名生成（拼音或去除非字母数字，首字母大写）
            base_username = re.sub(r'[^a-zA-Z0-9]', '', customer.username)
            if not base_username:
                base_username = 'user'
            username = base_username.lower()
            suffix = 0
            final_username = username
            while User.objects.filter(username=final_username).exists():
                suffix += 1
                final_username = f"{username}{suffix}"
            user = User.objects.create_user(username=final_username, password='123456')
            user.is_active = True
            user.save()
            customer.user = user
        customer.save()
        receiver = request.POST.get('receiver')
        delivery_phone = request.POST.get('delivery_phone')
        delivery_address = request.POST.get('delivery_address')
        if address_obj:
            address_obj.receiver = receiver
            address_obj.phone = delivery_phone
            address_obj.address = delivery_address
            address_obj.save()
        else:
            Address.objects.create(customer=customer, receiver=receiver, phone=delivery_phone, address=delivery_address)
        return redirect('customer_list')
    return render(request, 'customer/edit.html', {'customer': customer, 'address': address_obj})


@login_required
def price_config_list_view(request, customer_id):
    """
    单价配置列表视图，展示指定客户的所有单价配置。
    :param request: HttpRequest对象
    :param customer_id: 客户ID
    :return: 渲染单价配置列表页面
    """
    customer = get_object_or_404(Customer, id=customer_id)
    configs = UserPriceConfig.objects.filter(customer=customer, delete_at__isnull=True)
    return render(request, 'customer/price_config.html', {'customer': customer, 'configs': configs})


@login_required
def price_config_create_view(request, customer_id):
    """
    单价配置创建视图，处理单价配置表单提交。
    :param request: HttpRequest对象
    :param customer_id: 客户ID
    :return: 渲染单价配置创建页面或跳转到列表
    """
    from LogisticsCard.models import Package
    customer = get_object_or_404(Customer, id=customer_id)
    packages = Package.objects.filter(delete_at__isnull=True)
    error_msg = ''
    if request.method == 'POST':
        package_name = request.POST.get('package')
        price = request.POST.get('price')
        # 唯一性校验：同客户同资费包只能有一个配置
        exists = UserPriceConfig.objects.filter(customer=customer, package=package_name, delete_at__isnull=True).exists()
        if exists:
            error_msg = f'该客户的资费包“{package_name}”已存在单价配置！'
        else:
            package_obj = packages.filter(name=package_name).first()
            if package_obj:
                price = package_obj.price
            UserPriceConfig.objects.create(
                customer=customer,
                package=package_name,
                channel_no='',  # 移除通道号，留空
                price=price
            )
            return redirect('price_config_list', customer_id=customer.id)
    return render(request, 'customer/price_config_create.html', {'customer': customer, 'packages': packages, 'error_msg': error_msg})


@login_required
def customer_delete_view(request, customer_id):
    from django.utils import timezone
    customer = get_object_or_404(Customer, id=customer_id, delete_at__isnull=True)
    customer.delete_at = timezone.now()
    customer.save()
    return redirect('customer_list')

@login_required
def customer_generate_user_view(request, customer_id):
    from django.contrib.auth.models import User
    import re
    customer = get_object_or_404(Customer, id=customer_id)
    if not customer.user:
        # 英文用户名生成（拼音或去除非字母数字，首字母大写）
        base_username = re.sub(r'[^a-zA-Z0-9]', '', customer.username)
        if not base_username:
            base_username = 'user'
        username = base_username.lower()
        suffix = 0
        final_username = username
        while User.objects.filter(username=final_username).exists():
            suffix += 1
            final_username = f"{username}{suffix}"
        user = User.objects.create_user(username=final_username, password='123456')
        user.is_active = True
        user.save()
        customer.user = user
        customer.save()
    return redirect('customer_list')
